//创建用户相关的小仓库
import { defineStore } from 'pinia'
import { login } from '@/api/user'
//引用数据类型
import type { loginForm, loginResponseForm } from '@/api/user/type.ts'
import type { UserState } from './types/type'
import { SET_TOKEN, GET_TOKEN } from '@/utils/token'
import { constantRouters } from '@/router/routers'
let useUserStore = defineStore('user', {
  //小仓库存储数据的地方
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用户唯一标识token
      menuRouters: constantRouters,
    }
  },
  //异步/处理逻辑的地方
  actions: {
    //用户登录
    async userLogin(data: loginForm) {
      let res: loginResponseForm = await login(data)
      if (res.code == 200) {
        //pinia仓库存储一下token
        //由于pinia|vuex存储数据其实利用的js对象
        this.token = res.data.token as string
        //pinia数据不是持久化，需要存在本地持久化
        SET_TOKEN(res.data.token as string)
        return 'OK'
      } else {
        return Promise.reject(new Error(res.data.message))
      }
    },
  },
  //获取数据的地方
  getters: {},
})
export default useUserStore
